package com.woniushop.web.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.woniushop.entity.PageBean;
import com.woniushop.entity.User;
import com.woniushop.service.OrderFormService;
import com.woniushop.service.UserService;
import com.woniushop.service.imple.OrderFormServiceImple;
import com.woniushop.service.imple.UserServiceImple;
import com.woniushop.utils.ControllerUtils;

/**
 * Servlet implementation class UserServlet
 */
@WebServlet("/user")
public class UserServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private UserService userService = new UserServiceImple();
	private OrderFormService orderFormService = new OrderFormServiceImple();

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String opr = request.getParameter("opr");
		switch (opr) {
		case "adminLogin":// 管理员登录
			adminLogin(request, response);
			break;
		case "adminLogout":// 管理员退出登录
			adminLogout(request, response);
			break;
		case "updateUname":// 修改登录用户的昵称
			updateUname(request, response);
			break;
		case "updateUpsw":// 修改登录用户的密码
			updateUpsw(request, response);
			break;
		case "list":// 分页查询所有用户
			list(request, response);
			break;
		case "checkUaccount":// 检查账号是否唯一
			checkUaccount(request, response);
			break;
		case "addAdmin":// 增加管理员账号
			addAdmin(request, response);
			break;
		case "resetUpsw":// 重置用户密码
			resetUpsw(request, response);
			break;
		case "changeUstate":// 修改用户状态
			changeUstate(request, response);
			break;
		case "changeUrole":// 修改用户角色
			changeUrole(request, response);
			break;
		case "addUser":// 增加商城用户
			addUser(request, response);
			break;
		case "userLogin":// 商城用户登录
			userLogin(request, response);
			break;
		case "userLogout":// 商城用户退出登录
			userLogout(request, response);
			break;
		default:

			break;
		}
	}

	private void userLogout(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 清除session数据
		request.getSession().invalidate();

		// 返回商城主页
		response.sendRedirect("index.jsp");
	}

	private void userLogin(HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		// 创建map用来传递JSON数据
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			// 根据前端数据创建user实例
			Map<String, String[]> parameterMap = request.getParameterMap();
			User user = (User) ControllerUtils.mapToObject(parameterMap, User.class);

			// 登录
			User loginUser = userService.login(user);

			// 写入返回值
			if (loginUser == null) {
				map.put("msg", "账号或密码错误！");
			} else if (loginUser.getUrole() != 3) {
				map.put("msg", "非商城用户账号，禁止登入！");
			} else if (loginUser.getUstate() != 1) {
				map.put("msg", "该账号已被禁用！");
			} else {
				if (loginUser.getUcartid() == 0) {
					// 如果商城用户没有购物车，则新建一个购物车
					String ucartno = orderFormService.creatCart(loginUser.getUid());
					// 将购物车id存入用户数据表中
					Integer ucartid = orderFormService.getOidByOno(ucartno);
					loginUser.setUcartid(ucartid);
					userService.update(loginUser);
				}
				map.put("msg", "ok");
				request.getSession().setAttribute("loginUser", loginUser);
			}
		} catch (Exception e) {
			map.put("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}

		// 返回JSON
		ControllerUtils.returnJson(map, response);
	}

	private void addUser(HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		// 创建map用来传递JSON数据
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			// 获得用户对象
			Map<String, String[]> parameterMap = request.getParameterMap();
			User user = (User) ControllerUtils.mapToObject(parameterMap, User.class);

			// 判断账号是否被占用
			if (user != null && userService.checkUaccount(user.getUaccount())) {
				user.setUrole(3);
				userService.reg(user);
				map.put("msg", "ok");
			} else {
				map.put("msg", "used");
			}
		} catch (Exception e) {
			map.put("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}

		// 返回JSON
		ControllerUtils.returnJson(map, response);
	}

	private void changeUrole(HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		// 创建map用来传递JSON数据
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			// 获得登录的用户信息
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			// 如果登录用户为null，则返回msg为null
			if (loginUser == null || loginUser.getUstate() == 2 || loginUser.getUrole() != 1) {
				map.put("msg", "null");
			} else {
				// 获得用户id
				Integer uid = Integer.parseInt(request.getParameter("uid"));
				// 获得用户目标状态
				Integer urole = Integer.parseInt(request.getParameter("urole"));
				// 重置用户密码
				userService.changeUrole(uid, urole);
				map.put("msg", "ok");
			}
		} catch (Exception e) {
			map.put("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}

		// 返回JSON
		ControllerUtils.returnJson(map, response);

	}

	/**
	 * 修改用户状态
	 * 
	 * @param request
	 * @param response
	 * @throws JsonGenerationException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	private void changeUstate(HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		// 创建map用来传递JSON数据
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			// 获得登录的用户信息
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			// 如果登录用户为null，则返回msg为null
			if (loginUser == null || loginUser.getUstate() == 2 || loginUser.getUrole() != 1) {
				map.put("msg", "null");
			} else {
				// 获得用户id
				Integer uid = Integer.parseInt(request.getParameter("uid"));
				// 获得用户目标状态
				Integer ustate = Integer.parseInt(request.getParameter("ustate"));
				// 修改用户状态
				userService.changeUstate(uid, ustate);
				map.put("msg", "ok");
			}
		} catch (Exception e) {
			map.put("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}

		// 返回JSON
		ControllerUtils.returnJson(map, response);
	}

	/**
	 * 重置用户密码
	 * 
	 * @param request
	 * @param response
	 * @throws JsonGenerationException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	private void resetUpsw(HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		// 创建map用来传递JSON数据
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			// 获得登录的用户信息
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			// 如果登录用户为null，则返回msg为null
			if (loginUser == null || loginUser.getUstate() == 2 || loginUser.getUrole() != 1) {
				map.put("msg", "null");
			} else {
				// 获得用户id
				Integer uid = Integer.parseInt(request.getParameter("uid"));
				// 重置用户密码
				userService.resetUpsw(uid);
				map.put("msg", "ok");
			}
		} catch (Exception e) {
			map.put("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}

		// 返回JSON
		ControllerUtils.returnJson(map, response);
	}

	/**
	 * 增加管理员账号
	 * 
	 * @param request
	 * @param response
	 * @throws JsonGenerationException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	private void addAdmin(HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		// 创建map用来传递JSON数据
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			// 获得登录用户
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			if (loginUser == null || loginUser.getUstate() == 2 || loginUser.getUrole() != 1) {
				map.put("msg", "null");
			} else {
				// 获得用户对象
				Map<String, String[]> parameterMap = request.getParameterMap();
				User user = (User) ControllerUtils.mapToObject(parameterMap, User.class);

				// 判断账号是否被占用
				if (user != null && userService.checkUaccount(user.getUaccount())) {
					userService.reg(user);
					map.put("msg", "ok");
				} else {
					map.put("msg", "used");
				}
			}

		} catch (

		Exception e) {
			map.put("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}

		// 返回JSON
		ControllerUtils.returnJson(map, response);
	}

	/**
	 * 检查账号是否唯一
	 * 
	 * @param request
	 * @param response
	 * @throws JsonGenerationException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	private void checkUaccount(HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		// 创建map用来传递JSON数据
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			// 获得账号
			String uaccount = request.getParameter("uaccount");
			// 判断账号是否被占用
			if (uaccount != null && userService.checkUaccount(uaccount)) {
				map.put("msg", "ok");
			} else {
				map.put("msg", "used");
			}
		} catch (Exception e) {
			map.put("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}

		// 返回JSON
		ControllerUtils.returnJson(map, response);
	}

	/**
	 * 分页无条件查询所有用户
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 创建map用来传递JSON数据
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// 创建pageBean
			PageBean pageBean = new PageBean();

			// 获得页码，如果没有页码，则设置页码为1
			String page = request.getParameter("page");
			if (page == null || page.trim().length() == 0 || Integer.parseInt(page) < 1) {
				pageBean.setPage(1);
			} else {
				pageBean.setPage(Integer.parseInt(page));
			}

			// 设置分页大小
			pageBean.setPageSize(5);

			// 获得分页数据
			List<User> list = userService.findByPage(pageBean, new User());
			map.put("list", list);
			map.put("pageBean", pageBean);
			map.put("msg", "ok");
		} catch (Exception e) {
			map.put("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}

		// 返回JSON
		ControllerUtils.returnJson(map, response);
	}

	/**
	 * 修改登录用户的密码
	 * 
	 * @param request
	 * @param response
	 * @throws JsonGenerationException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	private void updateUpsw(HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		// 创建map用来传递JSON数据
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			// 获得登录的用户信息
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			// 如果登录用户为null，则返回msg为null
			if (loginUser == null || loginUser.getUstate() == 2) {
				map.put("msg", "null");
			} else {
				// 获得原密码
				String oldUpsw = request.getParameter("oldUpsw");
				// 如果密码吻合，则进行修改，否则返回出错信息
				if (loginUser.getUpsw().equals(oldUpsw)) {
					// 获得修改后的密码
					String upsw = request.getParameter("upsw");
					// 修改密码
					loginUser.setUpsw(upsw);
					userService.update(loginUser);
					map.put("msg", "ok");
				} else {
					map.put("msg", "原密码错误！");
				}
			}
		} catch (Exception e) {
			map.put("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}

		// 返回JSON
		ControllerUtils.returnJson(map, response);
	}

	/**
	 * 修改登录用户的昵称
	 * 
	 * @param request
	 * @param response
	 * @throws JsonGenerationException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	private void updateUname(HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		// 创建map用来传递JSON数据
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			// 获得登录的用户信息
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			// 如果登录用户为null，则返回msg为null
			if (loginUser == null || loginUser.getUstate() == 2) {
				map.put("msg", "null");
			} else {
				// 获得修改后的昵称
				String uname = request.getParameter("uname");
				// 修改昵称
				loginUser.setUname(uname);
				userService.update(loginUser);
				map.put("msg", "ok");
			}
		} catch (Exception e) {
			map.put("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}

		// 返回JSON
		ControllerUtils.returnJson(map, response);
	}

	/**
	 * 管理员退出登录
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void adminLogout(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 清除session数据
		request.getSession().invalidate();

		// 返回到登录页面
		response.sendRedirect("manage/login.jsp");
	}

	/**
	 * 管理员登录
	 * 
	 * @param request
	 * @param response
	 * @throws JsonGenerationException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	private void adminLogin(HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		// 创建map用来传递JSON数据
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			// 根据前端数据创建user实例
			Map<String, String[]> parameterMap = request.getParameterMap();
			User user = (User) ControllerUtils.mapToObject(parameterMap, User.class);

			// 登录
			User loginUser = userService.login(user);

			// 写入返回值
			if (loginUser == null) {
				map.put("msg", "账号或密码错误！");
			} else if (loginUser.getUrole() == 3) {
				map.put("msg", "非管理员账号，禁止登入！");
			} else if (loginUser.getUstate() != 1) {
				map.put("msg", "该账号已被禁用！");
			} else {
				map.put("msg", "ok");
				request.getSession().setAttribute("loginUser", loginUser);
			}
		} catch (Exception e) {
			map.put("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}

		// 返回JSON
		ControllerUtils.returnJson(map, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
